package top.saiyin.list;

/**
 * @Program: leetcode
 * @Description: 最长公共前缀
 * @Author: sy
 * @Create: 2020-08-25
 **/
public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        String[] strs2 = {"dog", "racecar", "car"};
        String[] strs3 = {"dog", ""};
        String[] strs4 = {"c", "acc", "ccc"};
        System.out.println(longestCommonPrefix(strs4));
    }

    public static String longestCommonPrefix(String[] strs) {
        // 边界条件
        if (strs.length == 0) {
            return "";
        }
        // 随便取一个
        String ans = strs[0];
        // 第一层遍历，为了判断公共前缀和数组中每个每个元素都比较一次
        for (int i = 1; i < strs.length; i++) {
            int j = 0;
            // 二层遍历，为了逐一比较公共前缀的每一个字母
            for (; j < ans.length() && j < strs[i].length(); j++) {
                if (ans.charAt(j) != strs[i].charAt(j)) {
                    break;
                }
            }
            ans = ans.substring(0, j);
            if ("".equals(ans)) {
                return ans;
            }
        }
        return ans;
    }
}
